package mp3player;
import java.net.URL;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.DurationUpdateEvent;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.Player;


// Javadoc http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/apidocs/javax/media/ControllerEvent.html

public class MP3Player {
	
	private List<EventListener> mp3PlayerListener = new ArrayList<EventListener>();

	private Player player;
	
	private boolean playing;

	public MP3Player() {
		playing = false;
	}
	
	public void stop() {
		player.stop();
		player.close();
		player = null;
		playing = false;
		Runtime.getRuntime().gc();
	}
	
	public void play(URL url) throws MP3PlayerException {
		try {
			
			if (playing) 
				stop();
			
			player = Manager.createPlayer(url);
			playing = true;
			
		} catch (java.io.IOException e) {
			throw new MP3PlayerException(e.getMessage());
		} catch (javax.media.NoPlayerException e) {
			throw new MP3PlayerException(e.getMessage());
		}

		player.addControllerListener(new ControllerListener() {
			
			public void controllerUpdate(ControllerEvent e) {
				if (e instanceof EndOfMediaEvent) {
					
					stop();
					notifyEndOfMedia();
					
				} else if (e instanceof DurationUpdateEvent) {
					
					DurationUpdateEvent event = (DurationUpdateEvent) e;
					notifyUpdateDuration(event.getDuration().getNanoseconds());
					
				}
			}
			
		});
		
		player.realize();
		player.start();
	}

	public void run() {
		
	}
	
	public void addMP3PlayerListener(MP3PlayerListener listener) {
		mp3PlayerListener.add(listener);
	}
	
	public boolean isPlaying() {
		return playing;
	}
	
	private void notifyEndOfMedia() {
		for (EventListener listener : mp3PlayerListener) {
			if (listener instanceof MP3PlayerListener) {
				// Eventuell in einem Worker Thread abarbeiten
				((MP3PlayerListener) listener).endOfMedia();
			}
		}
	}
	
	private void notifyUpdateDuration(long nanoseconds) {
		for (EventListener listener : mp3PlayerListener) {
			if (listener instanceof MP3PlayerListener) {
				// Eventuell in einem Worker Thread abarbeiten
				((MP3PlayerListener) listener).durationUpdate(nanoseconds);
			}
		}
	}

	

	

}
